package data

import (
	"fmt"
	"github.com/robfig/cron/v3"
	"log/slog"
	"rule/model"
	"sync"
)

type RuleListStruct struct {
	mu      sync.Mutex
	idMap   map[string]string         // key 是乐山id, value 是规则id
	ruleMap map[string]*model.RuleDef // key 是乐山id,
}

func SetupJob() {
	IdTaskMap = make(map[string]cron.EntryID)
	Jobs = cron.New(cron.WithSeconds())
	Jobs.Start()
}

func LoadDelayTask() {
	_, err := Jobs.AddFunc("@every 1s", processDelayTask) // 等价于6个星 "* * * * * *"
	if err != nil {
		slog.Error("LoadDelayTask_err", "err", err.Error())
		return
	}
	slog.Debug("LoadDelayTask成功")
}

func NewRuleList() *RuleListStruct {
	return &RuleListStruct{
		idMap:   make(map[string]string),
		ruleMap: make(map[string]*model.RuleDef),
	}
}

func (r *RuleListStruct) AddOrUpdate(_ruleDef *model.RuleDef) {
	r.mu.Lock()
	defer r.mu.Unlock()

	// 新增进去 要判断规则id 是否存的的
	id := _ruleDef.Id
	_, ok := r.idMap[id]
	if ok {
		// 已经存在需要,删除任务
		_t, ok2 := IdTaskMap[id]
		if ok2 {
			delete(IdTaskMap, id)
			Jobs.Remove(_t)
		}

	} else {
		r.idMap[id] = _ruleDef.RuleId
	}
	r.ruleMap[id] = _ruleDef

	// 启用状态
	if _ruleDef.Status == "1" {
		// 定时任务创建一个
		_spec := fmt.Sprintf("@every %vs", _ruleDef.AlarmTime)
		_fc := func() { ruleWork(_ruleDef) }
		eId, err := Jobs.AddFunc(_spec, _fc)
		if err != nil {
			slog.Error("AddFunc_err", "err", err.Error())
		}
		IdTaskMap[id] = eId
	}
}

func (r *RuleListStruct) Remove(id string) {
	r.mu.Lock()
	defer r.mu.Unlock()
	//
	delete(r.idMap, id)
	delete(r.ruleMap, id)
	_t, ok := IdTaskMap[id]
	if ok {
		delete(IdTaskMap, id)
		Jobs.Remove(_t)
	}
	// return nil
}
